package cn.yuanqiao.archive.wenjianzhengli.aspect;

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.wenjianzhengli.annotation.JudgeIsManualAdd;
import cn.yuanqiao.common.exception.ServiceException;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

@Aspect
@Component
public class JudgeIsManualAspect {

    private static final Logger log = LoggerFactory.getLogger(JudgeIsManualAspect.class);

    @Resource
    private TenantCategoryMapper tenantCategoryMapper;

    @Pointcut("@annotation(cn.yuanqiao.archive.wenjianzhengli.annotation.JudgeIsManualAdd)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void before(JoinPoint point){
        MethodSignature signature = (MethodSignature) point.getSignature();
        // 获取方法
        Method method = signature.getMethod();
        JudgeIsManualAdd annotation = method.getAnnotation(JudgeIsManualAdd.class);
        String type = annotation.type();
        Object[] args = point.getArgs();
        JSONObject arg = (JSONObject) args[0];
        JSONArray array = arg.getJSONArray("column");
        JSONObject object1 = new JSONObject();
        object1.put("name","JS_TYPE");
        object1.put("value","1");
        array.add(object1);
        JSONObject object2 = new JSONObject();
        object2.put("name","IS_MANUAL_ADD");
        object2.put("value","1");
        array.add(object2);
        Long categoryId = arg.getLong("categoryId");
        TenantCategory category = new TenantCategory();
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
        log.info("进去判断是否存在IS_MANUAL_ADD字段的前置通知");
        log.info("type======{}",type);
        log.info("categoryId======{}",categoryId);
        String tableName = "3".equals(type)?tenantCategory.getItemTableName():"0".equals(type)?tenantCategory.getFileTableName():"1".equals(type)?tenantCategory.getFolderTableName():"";
        String allFieldOfTable = "";
        if(!"".equals(tableName)){
            allFieldOfTable = tenantCategoryMapper.getAllFieldOfTable(tableName);
        }
        if(!"".equals(allFieldOfTable)){
            List<String> colList = Arrays.asList(allFieldOfTable.split(","));
            if(!colList.contains("IS_MANUAL_ADD") && !colList.contains("is_manual_add")){
                throw new ServiceException("该门类未添加IS_MANUAL_ADD字段");
            }
        }
    }
}
